<template>
  <div class="itforTree">
    <a-row>
      <a-col :span="20" @click="topTree">
        <svg-icon name="company" />
        <span style="margin-left: 8px;cursor:pointer;font-weight: bold" :class="ifTree ? '' : 'treeTop'">
          {{ companyName || state.menuList[0]?.name }}
        </span>
      </a-col>
      <a-col :span="4" style="display: flex; justify-content: flex-end">
        <a-dropdown v-model:open="dropdownVisible">
          <i class="fa fa fa-angle-down fa-2x" @click.prevent />
          <template #overlay>
            <a-menu class="menu-list" @click="handleMenuClick">
              <a-menu-item key="search" v-if="state.menuList?.length > 10">
              </a-menu-item>
              <a-menu-item v-for="(item, index) in state.menuList" :key="index" @click="onSwitch(item.id)">
                {{ item.name }}
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
    </a-row>

    <a-row type="flex" align="middle" justify="space-between" style="overflow: hidden;">
      <a-col :span="12" style="display: flex;align-items: center;">
        <!-- background-color: #ffffff -->
        <!-- <a-input allowClear style="width: 9vw;" v-model:value="searchValue"
          :placeholder="`${$t('search')}...`" />
        <a-button type="" class="search" @click="SearchTree"><i class="fa fa-search-plus" />
        </a-button> -->
        <a-input-group compact style="">
          <a-input @select="handleSelect" @input="handleInput" :bordered="false" @clear="handlerClear" allowClear
            style="width: 8.2vw;background-color: #ffffff;height: 32.86px" v-model:value="searchValue"
            :placeholder="`${$t('search')}...`" />
          <a-button type="" class="search" @click="SearchTree"><i class="fa fa-search-plus" /></a-button>
        </a-input-group>
      </a-col>
      <a-col :span="12" style="display: flex;align-items: center;justify-content: center;">
        <span style="font-size: 12px;text-align: left;">{{ $t('职位类型') }}:</span>
        <a-select :getPopupContainer="(triggerNode) => triggerNode.parentNode" ref="select" style="margin-left: 5px"
          v-model:value="state.selectedPositionType" :options="hooks.treeHook.selectPositionType"
          @change="getSelectValue" :placeholder="$t('请选择')" :fieldNames="{
            label: isCn ? 'descZh' : isEn ? 'dictDesc' : 'descAr',
            value: 'dictData',
          }">
        </a-select>
      </a-col>
    </a-row>

    <a-divider />
    <div class="boxTree">
      <a-tree ref="treeRef" v-model:expandedKeys="expandedKeys" v-if="refresh && list?.length" :treeData="list"
        :showIcon="true" v-model:checkedKeys="checkedKeys" v-model:selectedKeys="treeCurrentKey" :fieldNames="{
          // children: 'children',
          key: 'id',
        }" :class="defaultValue === 'arabic' ? 'arabic' : 'default'" @select="treeCheck">
        <template #title="{
          unitTypeIcon,
          nameEn,
          nameZh,
          nameAr,
          employeeCount,
          children
        }">
          <div class="title-count">
            <div style="display: flex; align-items: center">
              <svg-icon style="margin-top: 2px; color: currentColor" :name="unitTypeIcon" />
              <span style="
                  font-size: 12px;
                  margin-right: 5px;
                  margin-left: 5px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  width: 9vw;
                ">
                <span :style="{ fontWeight: children?.length > 0 ? '500' : '' }"
                  :title="isEn ? nameEn : isCn ? nameZh ?? nameEn : nameAr ?? nameEn">
                  {{
                    isCn && nameZh ? nameZh : isArabic && nameAr ? nameAr : nameEn
                  }}
                </span>
              </span>
            </div>
            <span style="color: #9c580e;margin-right: 13.5px">
              {{ employeeCount === 0 ? "" : employeeCount }}
            </span>
          </div>
        </template>
        <template #switcherIcon="{ switcherCls, employeeCount }">
          <div class="swit-count">
            <i style="margin-top: 3px;margin-left: 10px" :class="switcherCls" class="fa fa-angle-up up fa-2x" />
          </div>
        </template>
      </a-tree>
      <div v-if="refresh && list.length === 0">
        {{ $t('没有数据') }}
      </div>
    </div>
  </div>
</template>
<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import ItforceLoading from "../itforce-loading/itforce-loading.vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["treeEmint", "companyIdChange", "getChoosedPositionType"]);
const dvLoading = ref(true);
const refresh = ref(true);
const props = defineProps({
  menuList: { type: Array, default: [] },
  treeData: { type: Array, default: [] },
  id: { type: [String, Number], default: "" },
  defaultStyle: { type: String, default: "" },
  c: [Number],
  refreshed: [Boolean],
});
import hooks, { useLanguage } from "@/hooks";
const { isEn, isCn } = useLanguage()
import { getCodeDict } from "@/utils/common/common";
const companyName = ref(null);
const orgNum = ref(null);
const ifTree = ref(false);
const searchValue = ref(null);
const expandedKeys = ref([]);
const checkedKeys = ref([]);
const state = reactive({
  treeData: props.treeData && props.treeData?.length ? props.treeData : [],
  selectedPositionType: String(hooks.treeHook.choosedPositionType),
  menuList: cloneDeep(props.menuList)
});
watch(() => props.menuList, (v) => {
  state.menuList = v
}, { deep: true })
getCodeDict({ enterpriseId: props.companyId, dictKey: 'positionType' }).then(r => {
  hooks.treeHook.selectPositionType = r ?? []
})
const list = ref([])
const treeList = ref([])
const flattenTree = (tree, parentId = null) => {
  let flattened = [];
  for (let node of tree) {
    const cloned = { ...node, parentId };
    delete cloned.children; // 删除children属性，以便可以直接添加到结果数组中
    flattened.push(cloned);
    if (node.children && node.children.length > 0) {
      // 递归处理子节点
      flattened = flattened.concat(flattenTree(node.children, node));
    }
  }
  return flattened;
}
watch(
  () => props.treeData,
  (val) => {
    list.value = val
    treeList.value = flattenTree(val)
    expandedKeys.value = treeList.value.map(item => item.id)
  },
  {
    flush: 'post',
    deep: true,
    immediate: true
  }
);


watch(
  () => state.treeData,
  (val) => {
    list.value = val
    treeList.value = flattenTree(val)
    expandedKeys.value = treeList.value.map(item => item.id)
  },
  {
    flush: 'post',
    deep: true,
    immediate: true
  }
);
watch(() => props.parentId,
  (newVal) => {
    checkedKeys.value = newVal
  },
  {
    flush: 'post',
    immediate: true
  }
);

const handleInput = debounce((e) => {
  state.treeData = props.treeData;
}, 500);

const currentCompanyObj = ref({})
// 公司切换
const onSwitch = (id) => {
  let companyObj = props.menuList.find((item) => item.id === id);
  companyName.value = companyObj.name;
  searchValue.value = null;
  orgNum.value = companyObj.employeeCount;
  currentCompanyObj.value = companyObj
  emits("companyIdChange", companyObj);
};
function refreshTree() {
  refresh.value = false;
  nextTick(() => {
    refresh.value = true;
  })
}
const getSelectValue = (v) => {
  hooks.treeHook.choosedPositionType = Number(v);
  emits('getChoosedPositionType', Number(v), state.menuList?.filter((l) => l.id === props.id)[0])
}
watch(() => props.parentId,
  (newVal) => {
    checkedKeys.value = newVal
  },
  {
    flush: 'post',
    immediate: true
  }
);
watch(
  () => props.defaultStyle,
  (newVal) => {
    newVal && (ifTree.value = false);
  },
  { deep: true }
);
const defaultValue = ref("default");
watch(
  () => proxy.$i18n.locale,
  (newVal) => {
    if (newVal == "arabic") {
      defaultValue.value = "arabic";
    } else {
      defaultValue.value = "default";
    }
  },
  {
    deep: true,
  }
);
// tree 选中
const treeCurrentKey = ref(null);
const SearchTree = debounce(() => {
  const expanded = filterTreeData(props.treeData, searchValue.value);
  state.treeData = !searchValue.value ? props.treeData : expanded;
  // searchValue.value = searchValue.value;
}, 1000);
//andt
const filterTreeData = (tree, keyword) => {
  const filteredData = [];
  tree?.forEach((node) => {
    const newNode = { ...node };
    if (newNode.children) {
      newNode.children = filterTreeData(newNode.children, keyword);
    }
    if (newNode.shortNameEn?.toLowerCase().includes(keyword?.toLowerCase())) {
      filteredData.push(newNode);
    } else if (newNode.children && newNode.children.length > 0) {
      newNode.children = newNode.children.filter((child) =>
        child.shortNameEn?.toLowerCase().includes(keyword?.toLowerCase())
      );
      if (newNode.children.length > 0) {
        filteredData.push(newNode);
      }
    }
  });
  return filteredData;
};
// watch(searchValue, (value) => {
//   console.log('==========vassdadsa======>',value);
//   const expanded = filterTreeData(props.treeData, value);
//   state.treeData = !value ? props.treeData : expanded;
//   searchValue.value = value;
// });
const treeCheck = (v, selectedNodes) => {
  if (!v) ifTree.value = false
  else ifTree.value = true
  searchValue.value = null;
  emits("treeEmint", ifTree.value, selectedNodes.selectedNodes[0]);
};


watch(
  () => props.refreshed,
  (val) => {
    searchValue.value = null;
  },
  { deep: true }
);
const topTree = () => {
  nextTick(() => {
    ifTree.value = false
    treeCurrentKey.value = null
    checkedKeys.value = null
    emits('treeEmint', ifTree.value)
  })
  refreshTree()
};

const menuList = ref([])
watch(() => props.menuList,
  (newVal) => {
    menuList.value = newVal;
    dvLoading.value = false
  },
  {
    flush: 'post',
  }
);
const dropdownVisible = ref(false)
const menuValue = ref('')
const handleMenuClick = (e) => {
  if (e.key !== 'search') {
    dropdownVisible.value = false;
    menuValue.value = null
    menuList.value = props.menuList
  } else {
    dropdownVisible.value = true;
  }
}
const menuInputBlur = debounce(() => {
  if (menuValue.value) {
    menuList.value = menuList.value.filter((item) =>
      item.shortName?.toLowerCase().includes(menuValue.value?.toLowerCase())
    );
  } else {
    menuList.value = props.menuList
  }
}, 1000);
function changeTreeColor(isTreeC) {
  ifTree.value = isTreeC
  refresh.value = false
  dvLoading.value = true
  setTimeout(() => {
    refresh.value = true;
    treeCurrentKey.value = null;
    dvLoading.value = false
  }, 1000);
}


function refreshDvLoading() {
  setTimeout(() => {
    dvLoading.value = false
  }, 2000);

}
onUnmounted(() => {
  refreshDvLoading()
})
const rodList = () => {
  topTree()
}
defineExpose({
  changeTreeColor
})
</script>
<style lang="scss" scoped>
// @import url("@/pages/staff/css/common.scss");

.search {
  height: 32.86px;
  background-color: #fff;
  color: #676a6c;
  border: 1px solid #d9d9d9;
  border-radius: 0 3px 3px 0;
}

.itforTree {
  width: 100%;
  padding: 16px;
  background-color: #f2f2f2;
}

.boxTree {
  padding-bottom: 48px;
  height: 100vh;
  overflow: scroll;
}

.boxTree::-webkit-scrollbar {
  display: none;
}

.orgNumStyle {
  color: #9c5b0e;
  text-align: right;
  line-height: 35px;
  float: right;
}

.treeTop {
  color: #ff6700;
}

.a-icon--right {
  color: #cec0c4;
}

.margin-t-16 {
  margin-top: 16px;
}

// .title {
//   width: 100%;
// }

.fa-angle-down {
  color: #a7b1c2;
}

.title-count {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.swit-count {
  display: flex;
  align-items: center;
  height: 100%;
  color: #a7b1c2;
  font-size: 14px
}

.menu-list {
  max-height: 500px;
  overflow-y: scroll;
  min-width: 100px;
  text-align: left;

  &::-webkit-scrollbar {
    display: none
  }

  :deep(.ant-input) {
    border-bottom: none !important;
    background-color: white
  }
}

::v-deep {
  .ant-divider-horizontal {
    margin: 16px 0;
  }

  .ant-tree .ant-tree-list-holder-inner {
    background-color: #f2f2f2;
  }

  .ant-tree .ant-tree-treenode {
    width: 100%;
    border-bottom: 1px solid #d9d9d9;
  }

  .ant-tree .ant-tree-switcher {
    position: absolute;
    right: 0;
  }

  .ant-tree span.ant-tree-switcher.ant-tree-switcher_close .ant-tree-switcher-icon {
    transform: rotate(-180deg);
  }

  .ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected {
    background-color: #f2f2f2;
    color: #ff6700;
  }

  .ant-tree .ant-tree-switcher .ant-tree-switcher-icon {
    font-size: 20px;
  }


  .ant-tree .ant-tree-node-content-wrapper:hover {
    background-color: rgba(0, 0, 0, 0.01);
    color: #ff6700;
  }

  .ant-tree .ant-tree-node-content-wrapper {
    width: 100%;
  }

  .ant-tree .ant-tree-switcher {
    z-index: 1;
  }

  // 全局样式修改回来
  // .ant-input {
  //   border: 1px solid #dadada !important;
  //   // border-radius: 4px !important;
  //   background-color: #ffffff !important;
  // }

  // .ant-input:hover {
  //   border: 1px solid #d9d9d9 !important;
  // }

  // .ant-input-search>.ant-input-group>.ant-input-group-addon:last-child .ant-input-search-button {
  //   border-start-end-radius: 3px;
  //   border-end-end-radius: 3px;
  // }

  .ant-select .ant-select-arrow {
    color: #fff;
  }

  .ant-table-measure-row {
    display: none;
  }

  .ant-input {
    border-bottom: none !important;
    // border-radius: 4px !important;
  }

  .ant-input-affix-wrapper {
    border: 1px solid #dadada !important;
    height: 100%;
  }


  .ant-input-affix-wrapper>input.ant-input {
    padding: 4px 11px;
  }

  .ant-input-affix-wrapper:focus {
    border: 1px solid #d9d9d9 !important;
  }

  .ant-input-affix-wrapper:hover {
    border: 1px solid #d9d9d9 !important;
  }

  .ant-input-affix-wrapper .ant-input-suffix {
    padding-right: 4px;
  }

  .ant-input-group.ant-input-group-compact>*:first-child {
    border-start-start-radius: 6px;
    border-end-start-radius: 6px;
  }

  .ant-input-group.ant-input-group-compact>*:last-child {
    border-start-end-radius: 6px;
    border-end-end-radius: 6px;
  }
}
</style>
